export function getLastEvent() {
  return new Promise(resolve => {
    const eventTypes = [
      'click',
      'touchstart',
      'mousedown',
      'keydown',
      'mouseover'
    ]
    const eventListener = event => {
      event.stopPropagation()
      event.path = event.composedPath()
      resolve(event)
    }

    eventTypes.forEach(eventType => {
      document.addEventListener(eventType, eventListener, {
        capture: true,
        passive: true // 默认不阻止默认事件
      })
    })
  })
}

export function getLines(stack) {
  return stack
    .split('\n')
    .slice(1)
    .map(item => item.replace(/^\s+at\s+/g, ''))
    .join('^')
}

function generateSelector(arr) {
  return arr
    .reverse()
    .filter(element => {
      return element !== window && element !== document
    })
    .map(element => {
      let selector = ''
      if (element.id) {
        return `${element.nodeName.toLowerCase()}#${element.id}`
      } else if (element.className && typeof element.className === 'string') {
        return `${element.nodeName.toLowerCase()}.${element.className}`
      } else {
        selector = element.nodeName.toLowerCase()
      }
      return selector
    })
    .join(' ')
}

export function getSelector(pathOrTarget) {
  if (Array.isArray(pathOrTarget)) {
    return generateSelector(pathOrTarget)
  } else {
    // 如果是一个对象
    let path = []
    while (pathOrTarget) {
      path.push(pathOrTarget)
      pathOrTarget = pathOrTarget.parentNode
    }
    return generateSelector(path)
  }
}

export function onload(cb) {
  if (document.readyState === 'complete') {
    cb()
  } else {
    window.onload = cb
  }
}
